package com.sasis.webapp.validator;

import java.io.Serializable;
import java.util.StringTokenizer;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.validator.Field;
import org.apache.commons.validator.GenericValidator;
import org.apache.commons.validator.Validator;
import org.apache.commons.validator.ValidatorAction;
import org.apache.commons.validator.util.ValidatorUtils;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.validator.Resources;

public class UrlCheck implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -6388989512274067232L;

	public static boolean validateUrl(Object bean, ValidatorAction va,
			Field field, ActionMessages errors, Validator validator,
			HttpServletRequest request) {

		String value = null;
		if (isString(bean))
			value = (String) bean;
		else
			value = ValidatorUtils.getValueAsString(bean, field.getProperty());
		if (GenericValidator.isBlankOrNull(value))
			return true;

		if (GenericValidator.isBlankOrNull(value))
			return true;
		boolean allowallschemes = "true".equalsIgnoreCase(field
				.getVarValue("allowallschemes"));
		int options = allowallschemes ? 1 : 0;
		if ("true".equalsIgnoreCase(field.getVarValue("allow2slashes")))
			options += 2;
		if ("true".equalsIgnoreCase(field.getVarValue("nofragments")))
			options += 4;
		String schemesVar = allowallschemes ? null : field
				.getVarValue("schemes");
		if (options == 0 && schemesVar == null)
			if (GenericValidator.isUrl(value)) {
				return true;
			} else {
				errors.add(field.getKey(), Resources.getActionMessage(
						validator, request, va, field));
				return false;
			}
		String schemes[] = null;
		if (schemesVar != null) {
			StringTokenizer st = new StringTokenizer(schemesVar, ",");
			schemes = new String[st.countTokens()];
			int i = 0;
			while (st.hasMoreTokens())
				schemes[i++] = st.nextToken().trim();
		}
		UrlValidator urlValidator = new UrlValidator(schemes, options);
		if (urlValidator.isValid(value)) {
			return true;
		} else {
			errors.add(field.getKey(), Resources.getActionMessage(validator,
					request, va, field));
			return false;
		}
	}

	protected static boolean isString(Object o) {
		return o != null ? (java.lang.String.class).isInstance(o) : true;
	}

}
